package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.*;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.SettingVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SettingManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private UserService userService;

    @Reference // dubbo的
    private QuestionService questionService;

    @Reference
    private NotificationService notificationService;

    @Reference
    private BlackListService blackListService;

    @Reference
    private UserInfoService userInfoService;

    public ResponseEntity findSettingVo() {
        // 1.获取user对象
        User user = UserHolder.get();
        // 2.查询陌生人问题
        Question question = questionService.findByUserId(user.getId());
        // 3.查询推送通知
        Notification notification = notificationService.findByUserId(user.getId());
        // 4.构建并封装 vo
        SettingVo settingVo = new SettingVo();
        if (question != null) { // 陌生人封装
            settingVo.setStrangerQuestion(question.getStrangerQuestion());
        }
        if (notification != null) { // 推送 封装
            settingVo.setGonggaoNotification(notification.getGonggaoNotification());
            settingVo.setPinglunNotification(notification.getPinglunNotification());
            settingVo.setLikeNotification(notification.getLikeNotification());
        }
        // 用户信息
        settingVo.setId(user.getId());
        settingVo.setPhone(user.getPhone());

        return ResponseEntity.ok(settingVo);
    }

    public void setQuestion(String content) {
        // 1.获取用户id
        Long userId = UserHolder.get().getId();

        // 2.查询此用户的陌生人问题
        Question question = questionService.findByUserId(userId);

        if (question == null) { // 新增
            question = new Question();
            question.setUserId(userId);
            question.setStrangerQuestion(content);
            questionService.save(question);
        } else { // 修改
            question.setStrangerQuestion(content);
            questionService.update(question);
        }
    }

    public void setNotification(Notification notificationParam) {
        // 1.获取用户id
        Long usreId = UserHolder.get().getId();

        // 2.调用rpc查询
        Notification notification = notificationService.findByUserId(usreId);

        // 注意：新增和修改传递的实体类是不一致。。。
        if (notification == null) { // 新增
            notificationParam.setUserId(usreId);
            notificationService.save(notificationParam);
        } else {// 修改
            notification.setGonggaoNotification(notificationParam.getGonggaoNotification());
            notification.setLikeNotification(notificationParam.getLikeNotification());
            notification.setPinglunNotification(notificationParam.getPinglunNotification());
            notificationService.update(notification);
        }
    }

    // 分页查询黑名单
    public ResponseEntity findBlckListByPage(Integer pageNum, Integer pageSize) {
        // 1.获取登录人id
        Long userId = UserHolder.get().getId();
        // 2.调用rpc完成黑名单分页查询
        PageBeanVo pageBeanVo = blackListService.findByPage(userId, pageNum, pageSize);
        // 3.取出黑名单用户id列表
        List<BlackList> blackList = (List<BlackList>) pageBeanVo.getItems();
        // 4.遍历封装userInfoList列表
        List<UserInfo> userInfoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(blackList)) {
            for (BlackList black : blackList) {
                // 查询黑名单用户详情
                UserInfo userInfo = userInfoService.findByUserId(black.getBlackUserId());
                // 设置到用户详情列表中
                userInfoList.add(userInfo);
            }
        }
        // 5.将 userInfoList 重置到 分页对象
        pageBeanVo.setItems(userInfoList);
        // 6.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 移除黑名单
    public void deleteBlackList(Long blackUserId) {
        // 1.获取登录userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc移除黑名单
        blackListService.deleteByUserIdAndBlackUserId(userId, blackUserId);
    }
    public void sendCode(String phone) {
        //生成验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "123456";
        //发送验证码
        //smsTemplate.sendSms(phone, code);

        //把验证码存入redis设置有效时间为5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone,code, Duration.ofMinutes(5));
        System.out.println("cxc");
    }

    //验证码验证
    public Map<String,Boolean> verifyCode(String verificationCode) {
        User user = UserHolder.get();
        String phone = user.getPhone();
        Boolean verification=true;
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        if(!StringUtils.equals(verificationCode,redisCode)){
            System.out.println("验证码验证失败");
            verification=false;
        }
        Map<String,Boolean> map=new HashMap<>();
        map.put("verification",verification);
        return map;
    }

    //保存手机号
    public void saveNewPhone(String newPhone) {
        //先判断修改的账号有无注册
        if(userService.findByPhone(newPhone)!=null){
            //账号已注册，抛出异常
            throw new RuntimeException("该手机号已被注册");
        }
        //账号没有注册更新号码
        User user = UserHolder.get();
        user.setPhone(newPhone);
        userService.update(user);

    }
}
